import { Component, OnInit, OnDestroy } from '@angular/core';

import { Http } from '@angular/http';

import { AlertsService } from '../../modules/ng2-alerts';

import { Router } from '@angular/router';

import { Channel } from '../../utils/channel';

import { Util } from '../../utils/util';



@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.css'],
  providers: [Channel]
})
export class LoginPage implements OnInit {

  // 登录错误提示
  public error: boolean = false;

  // user
  public user: any;

  public source: any;

  eventOff: any;

  constructor(private http: Http, private _alert: AlertsService, private router: Router, private channel: Channel, private util: Util) {

  }

  ngOnInit() {

    // 删除用户保存
    this.util.sessionStore().delete('user');

    // user
    this.user = {
      nick: '',
      password: '',
      channel: 0,
      checked: false
    };

    if (this.util.store().has('remember')) {

      let s_user: any = this.util.store().get('remember');
      s_user.password = this.parseCode(s_user.password);

      this.user = s_user;
    }

    this.source = this.channel.init();

    this.user.channel = this.source.channel;


    console.log(this.source);
  }

  ngOnDestroy() {
    if (this.eventOff) {
      this.eventOff.unsubscribe();
    }

    if(this.alertEvent){
      this.alertEvent.unsubscribe();
    }
  }

  alertEvent:any;
  //login
  submit() {
    

    if (this.eventOff) {
      this.eventOff.unsubscribe();
    }

    this.eventOff = this.http.post('/qbmf/signIn', {
      nick: this.user.nick,
      password: this.user.password
    }).subscribe((response) => {
      console.log(response);

      this.alertEvent = this._alert.create('success', '登录成功', { duration: 2000 });

      setTimeout(() => {
        this.router.navigate(['/dashborad']);
      }, 1000);

      if (this.user.checked) {

        let _user: any = Object.assign({}, this.user);

        _user.password = this.encode(_user.password);

        this.util.store().set('remember', _user);
      }

      this.error = false;
    }, (error) => {
      // console.log('hhhhhhhhhhhhh');
      console.log(error);

      this.error = true;
    });
  }

  // 对密码加密
  encode(_password) {

    _password = _password.toString();

    let encodePass = [];
    for (let i = 0; i < _password.length; i++) {

      encodePass.push(_password.charCodeAt(i));
    }

    return encodePass;
  }

  // 对密码解密
  parseCode(enPassword) {
    let password = "";

    for (let i = 0; i < enPassword.length; i++) {

      let encodep = enPassword[i].toString();

      password += String.fromCharCode(encodep);
    }

    return password;
  }
}
